<template>
  <div class="employees-container">
    <div class="app-container">
      <PageTools>
        <!-- 插入到left插槽位置 -->
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <!-- 插入到right插槽位置 -->
        <template #right>
          <el-button type="warning" size="small" @click="$router.push('import')">导入excel</el-button>
          <el-button type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog = true">新增员工</el-button>
        </template>
      </PageTools>
      <el-card style="margin-top: 10px;">
        <el-table border :data="EmployeesList" :default-sort="{prop:'timeOfEntry',order:'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ formOfEmploymentFormat(row.formOfEmployment) || '未知' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" prop="" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            layout="total, sizes,prev, pager, next, jumper"
            :total="total"
            :page-size="size"
            :page-sizes="[2,5,10]"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工的弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog">
        <addOrEdit
          v-if="showDialog"
          @close="showDialog = false"
          @update-employee="hUpdateEmployee"
        />
      </el-dialog>
      <!-- 分配角色的弹层 -->
      <el-dialog
        :visible.sync="showDialogRole"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <assign-role v-if="showDialogRole" :cur-id="curId" @close="showDialogRole = false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import addOrEdit from '@/views/employees/empDialog.vue'
// import PageTools from '@/components/PageTools'
import { getEmployeesList, delEmployee } from '@/api/getEmployeesSimple'
import EmployeesEnum from '@/constant/employees'
console.log(EmployeesEnum.hireType, 'EmployeesEnum.hireType')
// const hireType = {}
// EmployeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// 装杯版
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})

console.log(hireType, 'hireType')
export default {
  name: 'Employees',
  components: {
    addOrEdit, AssignRole
  },
  data() {
    return {
      showDialogRole: false,
      showDialog: false,
      page: 1,
      size: 5,
      EmployeesList: [],
      total: 0,
      curId: ''
    }
  },
  created() {
    this.loadEmployeesList()
  },
  methods: {
    hAssignRole(id) {
      console.log(id)
      this.showDialogRole = true
      this.curId = id
    },
    formatData(list) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      console.log(list)
      let header = []
      // header = ['id', 'mobile', 'username', .....]
      // data = [
      //     ['65c2', '1380000002', '管理员', ....],
      //     ['65c3', '1380000003', '孙财', ....],
      // ]
      let data = []
      // 开始代码
      // 找到一个元素
      const one = list[0]
      if (!one) {
        return { header, data }
      }
      header = Object.keys(one).map(key => {
        return map[key]
      })

      // data把list中每一个对象转成 对应的value数组
      data = list.map(obj => {
        // 把  Obj['formOfEmployment']: 1 , 2   ---> '正式'， '非正式'
        const key = obj['formOfEmployment'] // 1, 2
        obj['formOfEmployment'] = hireType[key] || '未知' // hireTypEnmu:{1:'正式', '2':'非正式' }

        return Object.values(obj)
      })

      return { header, data }
    },
    hExportExcel() {
      // 1.发送请求,拿到真实的数据
      try {
        import('@/vendor/Export2Excel').then(async excel => {
          const res = await getEmployeesList({ page: this.page, size: this.size })
          console.log(res, 'excel')
          const list = res.data.rows
          // 2.将拿到的数据进行格式化操作
          const { header, data } = this.formatData(list)
          console.log('header', header)
          console.log('data', data)
          excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: 'excel-list', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
          })
        })
      } catch (error) {
        console.log(error)
      }
      // import('@/vendor/Export2Excel').then(excel => {
      //   console.log(excel)
      //   excel.export_json_to_excel({
      //     header: ['姓名', '工资'], // 表头 必填
      //     data: [
      //       ['刘备', 100],
      //       ['关羽', 500]
      //     ], // 具体数据 必填
      //     filename: 'excel-list', // 文件名称
      //     autoWidth: true, // 宽度是否自适应
      //     bookType: 'xlsx' // 生成的文件类型
      //   })
      // })
    },
    hUpdateEmployee() {
      // 关闭弹层
      this.showDialog = false
      // 到最后一页看数据
      this.total++
      this.page = Math.ceil(this.total / this.size)
      // 刷新页面
      this.loadEmployeesList()
    },
    // 实现删除
    async doDel(id) {
      try {
        await delEmployee(id)
        this.loadEmployeesList()
        this.$$message.success('删除成功')
        // 2. 如果当前表格中只有一条，删除之后自动请求上一页数据
        if (this.EmployeesList.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
      } catch (error) {
        console.log(error, 'delEmployee')
      }
    },
    hDel(id) {
      console.log(id)
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 确定
        this.doDel(id)
      }).catch(() => {
        // 取消
      })
    },
    handleSizeChange(val) {
      this.page = 1
      this.size = val
      this.loadEmployeesList()
    },
    handleCurrentChange(curPage) {
      this.page = curPage
      this.loadEmployeesList()
    },
    formOfEmploymentFormat(id) {
      // console.log(EmployeesEnum.hireType, 'EmployeesEnum.hireType')
      // const item = EmployeesEnum.hireType.find(item => item.id === id)
      // console.log(item)
      // if (item) {
      //   return item.value
      // } else {
      //   return '未知'
      // }
      // 优化
      return hireType[id]
    },
    async loadEmployeesList() {
      try {
        const res = await getEmployeesList({ page: this.page, size: this.size })
        console.log(res)
        this.EmployeesList = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
